package com.web.manager.jpush;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.connection.NettyHttpClient;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.CIDResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.netty.handler.codec.http.HttpMethod;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

/**
 * Created by xukk on 2017/7/10.
 */
@Slf4j
public class PushManage {
    private Logger logger = LoggerFactory.getLogger(PushManage.class);
    public static PushManage mg = new PushManage();

    public static void main(String[] args) {
        PushRequest request = new PushRequest();
        request.setALIAS_LIST(Lists.newArrayList("5"));
        request.setALERT("今天是三伏天");
        request.setTITLE("三伏天");
        request.setMSG_CONTENT("it is hot");
        //request.setREGISTRATION_ID_LIST(Lists.newArrayList("160a3797c833de8c5b1"));
        request.setType(1);
        Map map= Maps.newHashMap();
        map.put("name","xukk");
        request.setExtra(map);
        PushManage.mg.sendPushWithCallback(request);
    }



    public  void jPushMessage(String memberId, String alter, String title, String cotent, String extraInfo){
        PushRequest request = new PushRequest();
        request.setALIAS_LIST(Lists.newArrayList(memberId));
        request.setALERT(alter);
        request.setTITLE(title);
        request.setMSG_CONTENT(cotent);
        //request.setREGISTRATION_ID_LIST(Lists.newArrayList("160a3797c833de8c5b1"));
        request.setType(1);
        Map map= Maps.newHashMap();
        map.put("name",extraInfo);
        request.setExtra(map);
        try {
            Response response = PushManage.mg.sendPushWithCallback(request);
            logger.info(response + "");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Connection error, should retry later", e);
            logger.error("Should review the error, and fix the request", e);
        }
    }

    // 使用 NettyHttpClient 异步接口发送请求
    public Response sendPushWithCallback(PushRequest request) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
        final NettyHttpClient client = new NettyHttpClient(ServiceHelper.getBasicAuthorization(request.getAPP_KEY(), request.getMASTER_SECRET()),
                null, clientConfig);
        try {
            URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));
            PushPayload payload = null;
            switch (request.getType()) {
                case 1:
                    //推送别名
                    payload = buildPushObject_android_and_ios(request);
                    break;
                case 2:
                    //推送到IOS ANDORID winphone
                    payload = buildPushObject_all_all_alert(request);
                    break;
                case 3:
                    //推送到IOS ANDROID
                    payload = buildPushObject_android_and_ios(request);
                    break;
                case 4:
                    //request.setCid(getCidList(request).cidlist.get(0));
                    //getCidList(request);
                    // request.setCid("6367397aa1909f8364e0b6f1-ff90e2c7-c550-4ce8-8767-ea2f28b36199");
                    payload = buildPushObject_android_and_ios_cid(request);
                    break;
                default:
                    return Response.custom().failure("type is blank");
            }

            client.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
                @Override
                public void onSucceed(ResponseWrapper responseWrapper) {
                    log.info("Got result: " + responseWrapper.responseContent);
                }
            });
        } catch (URISyntaxException e) {
            log.warn("push error->{}", e.getMessage());
            return Response.custom().failure("push error");
        }
        return Response.custom().ok();
    }

    public CIDResult getCidList(PushRequest request) {
        JPushClient jPushClient = new JPushClient(request.getMASTER_SECRET(), request.getAPP_KEY());
        try {
            CIDResult result = jPushClient.getCidList(3, null);
            log.info("Got result - " + result);
            return result;

        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
        }
        return null;
    }

    public static PushPayload buildPushObject_all_all_alert(PushRequest request) {
        return PushPayload.alertAll(request.getALERT());
    }

    public static PushPayload buildPushObject_all_alias_alert(PushRequest request) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(request.getALIAS_LIST()))
                .setNotification(Notification.alert(request.getALERT()))
                .build();
    }

    public static PushPayload buildPushObject_android_tag_alertWithTitle(PushRequest request) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.tag(request.getTAG_LIST()))
                .setNotification(Notification.android(request.getALERT(), request.getTITLE(), null))
                .build();
    }

    public static PushPayload buildPushObject_android_and_ios(PushRequest request) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias( request.getALIAS_LIST()))
                .setNotification(Notification.newBuilder()
                        .setAlert(request.getALERT())
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setTitle(request.getTITLE()).build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .incrBadge(1).build())
                        .build()).setMessage((Message.newBuilder().setMsgContent(request.getMSG_CONTENT()).addExtras(request.getExtra()).build()))
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
    }


    public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage(PushRequest request) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.tag_and(request.getTAG_LIST()))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(request.getALERT())
                                .setBadge(5)
                                .setSound(request.getSound())
                                .addExtras(request.getExtra())
                                .build())
                        .build())
                .setMessage(Message.content(request.getMSG_CONTENT()))
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
    }

    public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras(PushRequest request) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.tag(request.getTAG_LIST()))
                        .addAudienceTarget(AudienceTarget.alias(request.getTAG_LIST()))
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(request.getMSG_CONTENT())
                        .addExtras(request.getExtra())
                        .build())
                .build();
    }

    public static PushPayload buildPushObject_all_tag_not(PushRequest request) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.tag_not(request.getTAG_LIST()))
                .setNotification(Notification.alert(request.getALERT()))
                .build();
    }

    public PushPayload buildPushObject_android_cid(PushRequest request) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.registrationId(request.getREGISTRATION_ID_LIST()))
                .setNotification(Notification.alert(request.getALERT()))
                .setCid(request.getIsCid() ? request.getCid() : null)
                .build();
    }

    public PushPayload buildPushObject_android_and_ios_cid(PushRequest request) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.registrationId("160a3797c833de8c5b1"))
                .setNotification(Notification.alert(request.getALERT()))
                .setCid(request.getCid())
                .build();
    }


}
